#include "headers/UserManager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

UserManager::UserManager(QObject *parent) : QObject(parent)
{
    initDatabase();
}

bool UserManager::initDatabase()
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("user_credentials.db");
    if (!m_db.open()) {
        qDebug() << "数据库打开失败：" << m_db.lastError().text();
        return false;
    }

    QSqlQuery query;
    QString createTable = "CREATE TABLE IF NOT EXISTS users ("
                          "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                          "username TEXT UNIQUE NOT NULL,"
                          "password_hash TEXT NOT NULL)";
    if (!query.exec(createTable)) {
        qDebug() << "创建用户表失败：" << query.lastError().text();
        m_db.close();
        return false;
    }
    return true;
}

QString UserManager::hashPassword(const QString &password)
{
    QCryptographicHash hash(QCryptographicHash::Sha256);
    hash.addData(password.toUtf8());
    return QString(hash.result().toHex());
}

bool UserManager::registerUser(const QString &username, const QString &password)
{
    if (username.isEmpty() || password.isEmpty()) return false;

    QSqlQuery query;
    query.prepare("INSERT INTO users (username, password_hash) VALUES (:username, :password_hash)");
    query.bindValue(":username", username);
    query.bindValue(":password_hash", hashPassword(password));

    if (!query.exec()) {
        if (query.lastError().text().contains("UNIQUE constraint failed"))
            return false; // 用户名已存在
        qDebug() << "注册失败：" << query.lastError().text();
        return false;
    }
    return true;
}

bool UserManager::loginUser(const QString &username, const QString &password)
{
    QSqlQuery query;
    query.prepare("SELECT password_hash FROM users WHERE username = :username");
    query.bindValue(":username", username);
    if (!query.exec() || !query.next()) {
        return false; // 用户名不存在
    }

    QString storedHash = query.value(0).toString();
    QString inputHash = hashPassword(password);
    return storedHash == inputHash;
}
